Project: Identify Customer Segments

In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task.

This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks. The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it.

It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. There will be times in the project where you will need to make and justify your own decisions on how to treat the data. These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made.

At the end of most sections, there will be a Markdown cell labeled Discussion. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.

Step 0: Load the Data

There are four files associated with this project (not including this one):

Each row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign.

To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the .csv data files in this project: they're semicolon (;) delimited, so you'll need an additional argument in your read_csv() call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely.

Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings.

Tip: Add additional cells to keep everything in reasonably-sized chunks! Keyboard shortcut esc --> a (press escape to enter command mode, then press the 'A' key) adds a new cell before the active cell, and esc --> b adds a new cell after the active cell. If you need to convert an active cell to a markdown cell, use esc --> m and to convert to a code cell, use esc --> y.

Step 1: Preprocessing

Step 1.1: Assess Missing Data

The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the Discussion cell with your findings and decisions at the end of each step that has one!

Step 1.1.1: Convert Missing Value Codes to NaNs

The fourth column of the feature attributes summary (loaded in above as feat_info) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest.

As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.

As we can see the cell below, there are a lot of columns that have missing values. Some columns have -1 meaning of missing values, 0 meaning of "unknown" values. So I would like to convert -1 values to np.nan values. By doing so, I want to differentiate missing values to unknown values.

Step 1.1.2: Assess Missing Data in Each Column

How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's hist() function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!)

For the remaining features, are there any patterns in which columns have, or share, missing data?

Discussion 1.1.2: Assess Missing Data in Each Column

We can see there are 6 columns that have more than 20% of missing values in the dataset. We need to drop those columns and keep the rest of the features to analyze the data.

Step 1.1.3: Assess Missing Data in Each Row

Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold.

In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values.

Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.

We can see that the variables with less missing rows and those with more missing rows show different distributions.

Even though I dropped rows which have more than 30% missing values, the distributions of both all dataset and dropped dataset are pretty similar, so I would like to drop 30% missing rows.

Discussion 1.1.3: Assess Missing Data in Each Row

Given the comparison between the fewer missing rows (<30%) and more missing rows (>30%) variable, they show the different distributions in 4 variables ('ZABEOTYP', 'SEMIO_TRADV', 'FINANZ_VORSORGER', 'GREEN_AVANTGARDE'). After that, I created the comparison plots (the dataset which were dropped the more missing rows (>30%) vs. full dataset), and 'SEMIO_TRADV', 'FINANZ_VORSORGER' show differences between these datasets but others look similar. So I decided to drop the rows which have more than 30% missing values for further analysis.

Step 1.2: Select and Re-Encode Features

Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (feat_info) for a summary of types of measurement.

In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns.

Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project!

3 categorical features and 1 mix feature were already dropped because they had a lot of missing values.

Step 1.2.1: Re-Encode Categorical Features

For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following:

Assess categorical variables: which are binary, which are multi-level, and which one needs to be re-encoded?

As we can see above, 'OST_WEST_KZ' has non-numeric values (W: west, O: east). So I will re-encode the values as 1, 2.

Discussion 1.2.1: Re-Encode Categorical Features

I keep numerical, ordinal and interval's 57 features without any re-encoding. I decided to drop 3 multi-categorical variables because there are similar columns of them and they could be redundant. For example, 'LP_FAMILIE_FEIN' shows family type and fine scale and 'LP_FAMILIE_GROB' shows family type, rough scale. These are similar information, so I decided to keep fewer levels of categorical variables, which is LP_FAMILIE_GROB. Finally, I dropped 'GFK_URLAUBERTYP', 'GEBAEUDETYP', 'CAMEO_DEUG_2015' because they have more than 6 levels of categories in each column

Step 1.2.2: Engineer Mixed-Type Features

There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices:

Be sure to check Data_Dictionary.md for the details needed to finish these tasks.

Even though LP_LEBENSPHASE_FEIN's dtype is float64, the data dictionary shows LP_LEBENSPHASE_FEIN is a categorical variable. Also, LP_LEBENSPHASE_FEIN and LP_LEBENSPHASE_GROB have similar information in terms of life stage, so I would like to keep fewer categorical levels which is LP_LEBENSPHASE_GROB.

Also, LP_LEBENSPHASE_GROB dtype is float64 because it has Null values, so I cannot change LP_LEBENSPHASE_GROB's dtype as int64 like other categorical variables.

WOHNLAGE have more than 6 levels of category so I will drop it

Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.

Dominating movement of person's youth (avantgarde vs. mainstream; east vs. west)

Investigate "CAMEO_INTL_2015" and engineer two new variables.

German CAMEO: Wealth / Life Stage Typology, mapped to international code

"CAMEO_INTL_2015" combines information on two axes: wealth and life stage. Break up the two-digit codes by their 'tens'-place and 'ones'-place digits into two new ordinal variables (which, for the purposes of this project, is equivalent to just treating them as their raw numeric values).

Discussion 1.2.2: Engineer Mixed-Type Features

We have 6 mix features (LP_LEBENSPHASE_FEIN, LP_LEBENSPHASE_GROB, PRAEGENDE_JUGENDJAHRE, WOHNLAGE, CAMEO_INTL_2015, PLZ8_BAUMAX).

Given the feature information, I decided to drop LP_LEBENSPHASE_FEIN, because it has similar information with LP_LEBENSPHASE_GROB but it has detailed information.

I dropped WOHNLAGE, because it has more than 6 levels of category.

Furthermore, I extracted two new variables from PRAEGENDE_JUGENDJAHRE, MAINSTREAM_AVANTGARDE and DECADE. The former one indicates whether Avantgarde or Mainstream is, and the latter one indicates the year information.

Finally, I created two new variables given CAMEO_INTL_2015 column, WEALTH and LIFE_STAGE. After feature engineering, I dropped two original columns, PRAEGENDE_JUGENDJAHRE and CAMEO_INTL_2015.

Step 1.2.3: Complete Feature Selection

In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following:

Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from the subset with few or no missing values.

We have 73 columns now, but lastly I would like to decide which columns I keep or drop.

We have columns that have similar information each other. For example:

We would like to drop some columns that have similar information: KBA05_ANTG1, KBA05_ANTG2, KBA05_ANTG3, KBA05_ANTG4, PLZ8_ANTG1, PLZ8_ANTG2, PLZ8_ANTG3, PLZ8_ANTG4.

I will keep columns: KBA05_GBZ, PLZ8_BAUMAX, PLZ8_HHZ, PLZ8_GBZ

Additionally, I decided to drop three columns and the reasons why:

Finally, I will use 64 columns for further analysis.

Step 1.3: Create a Cleaning Function

Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step.

Step 2: Feature Transformation

Step 2.1: Apply Feature Scaling

Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the API reference page for sklearn to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following:

Impute missing values by using mode for categorical and median for numerical variables

Discussion 2.1: Apply Feature Scaling

df_impute doesn't have any NaN values but by filling NaN with median for numerical variables and with mode for categorical variables. After that, I performed feature scaling.

Step 2.2: Perform Dimensionality Reduction

On your scaled data, you are now ready to apply dimensionality reduction techniques.

When we have 63 components, pca's result shows 91%

Discussion 2.2: Perform Dimensionality Reduction

Given the scree graph above, I chose 40 components which explains more than 90% of the variance.

Step 2.3: Interpret Principal Components

Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion.

As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend expect to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.

Positive weights

Negative weights

Positive weights

Negative weights

Positive weights

Negative weights

Discussion 2.3: Interpret Principal Components

Step 3: Clustering

Step 3.1: Apply Clustering to General Population

You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep.

Discussion 3.1: Apply Clustering to General Population

I decided to choose 15 clusters, because the plot shows that the SSE score drops significantly till k=15, then starts to flatten out.

Step 3.2: Apply All Steps to the Customer Data

Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data.

Step 3.3: Compare Customer Data to Demographics Data

At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is.

Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.

Take a look at the following points in this step:

As we can see the graph above, customer dataset and general population have similar results.

Discussion 3.3: Compare Customer Data to Demographics Data

Cluster 4 is overrepresented in the customers data and general population data. We can see some characteristics of group of population that are relative popular with the mail-order company:

Cluster 14 is underrepresented in the customers data and general population data. We can see some characteristics of group of population that are relatively unpopular with the company:

Congratulations on making it this far in the project! Before you finish, make sure to check through the entire notebook from top to bottom to make sure that your analysis follows a logical flow and all of your findings are documented in Discussion cells. Once you've checked over all of your work, you should export the notebook as an HTML document to submit for evaluation. You can do this from the menu, navigating to File -> Download as -> HTML (.html). You will submit both that document and this notebook for your project submission.